/**
@author: 王猛
@date: 2021-02-03
@Email：837821237@qq.com
*/
import React, { useState, useEffect } from "react"
import { companyType , companyName, reqProvinceCity, reqUpload, reqCompanyMember , reqSearchArea , reqExpertMember} from "../../../server/api";
import { createForm } from 'rc-form';
import { useHistory } from 'react-router-dom';
import './index.less';
import img1 from './img/img1.png'
import img2 from './img/img2.png'
import { NavBar, Icon, List, InputItem, Button, Checkbox, Toast ,Picker ,ImagePicker, TextareaItem, Modal} from 'antd-mobile';
const CheckboxItem = Checkbox.CheckboxItem;

const InviteAlliance = ({ form }) => {

    let history = useHistory();

    const { getFieldProps, getFieldValue, validateFields } = form;
    


    useEffect(() => {
       loadCompanyType(); 
       loadCompanyName();
       loadDistrict();
       loadSearchArea();
    }, []);

   
    // 表单提交
    const submitForm = () => {
        form.validateFields()
         .then(res=>{
            if(imgAddress.length===0){
                Toast.info('请上传营业执照');
                return
            }
            if(recImg.length===0){
                Toast.info('请上传回执单');
                return
            }
            console.log('res',res);
            let params = {};
            params.province = res.district[0];
            params.city = res.district[1];
            params.companyCode = res.companyCode;
            params.linkPerson = res.linkPerson;
            params.memberName = res.memberName[0];
            params.companyType = res.companyType[0];
            params.invitedCode = "WxuidB2fVxg=";
            //图片上传
            let imgResult1 =  upload(imgAddress);
            let imgResult2 =  upload(recImg);
            let userInfo = JSON.parse(sessionStorage.getItem('userInfo'))
            params.userId = userInfo.userId;
            params.memberPhone = userInfo.phoneNumber;
            Promise.all([...imgResult1,...imgResult2]).then(pRes=>{
                console.log(pRes);
                params.businessLicense = pRes[0].data.ret ? pRes[0].data.data :'';
                if (pRes.length===2){
                 params.receiptsUrl = pRes[1].data.ret ? pRes[1].data.data :'';
                } 
                if (pRes.length===3){
                 params.receiptsUrl = `${pRes[1].data.data},${pRes[2].data.data}`  ;
                } 
                console.log(params)
                reqCompanyMember(params).then(res=>{
                    console.log('联盟结果',res);
                    if (res.data.ret) {
                        Toast.success('加入成功')
                        return
                    }
                    Toast.info(res.data.errmsg)
                })
            })
        })
        .catch(err=>{
            for(let key in err.errors){
                Toast.info(err.errors[key].errors[0].message);
                return
            }
        })
        ;
    }
    
   const [district,setDistrict] = useState(''); //省市数据
   //加载省市数据
   const loadDistrict =() =>{
    reqProvinceCity().then(res=>{
        console.log(res)
        if(res&&res.data.ret){
           let options = res.data.data;
           options = JSON.parse(JSON.stringify(options).replace(/name/g,"label"));
           options = JSON.parse(JSON.stringify(options).replace(/regionId/g,"value"));
           setDistrict(options);
        }
        
    })
   }


   const [companyTypeData,setCompanyTypeData] = useState([]);//机构类型
    //加载机构类型
   const loadCompanyType =() =>{
    companyType().then(res=>{
        if(res&&res.data.ret){
            let resList = res.data.data.children;
            let resListNew = [];
           resList.map( (item) =>
             resListNew.push({value:item.code,label:item.value})
            )
            setCompanyTypeData(resListNew);
        }
    })
   }


   const [companyNameData,setCompanyNameData] = useState([]);//单位名称
   //加载单位名称
  const loadCompanyName =() =>{
    let params = {invitedCode:'WxuidB2fVxg='}; 
    companyName(params).then(res=>{
       console.log(res);
       if(res&&res.data.ret){
           let resList = res.data.data;
           let resListNew = [];
          resList.map( (item) =>
            resListNew.push({value:item.id,label:item.companyName})
           )
           setCompanyNameData(resListNew);
       }
   })
  }

  const [searchAreaData,setSearchAreaData] = useState([]);//研究领域
   //加载研究领域
  const loadSearchArea =() =>{ 
    reqSearchArea().then(res=>{
       console.log(res,'研究领域');
       if(res&&res.data.ret){
           let resList = res.data.data;
           let resListNew = [];
          resList.map( (item) =>
            resListNew.push({value:item.code,label:item.researchName})
           )
           setSearchAreaData(resListNew);
       }
   })
  }


    //页面返回
  const clickLeft = () => {
        history.goBack();
  }
  



   //单位营业执照图片地址
  const [imgAddress,setImgAddress] = useState([]);
   const onImgaeChange = (files, type, index) => {
    console.log(files, type, index);
    setImgAddress(files);

  }
  
  //单位回执单图片地址
   const [recImg,setRecImg] = useState([]);
   const onRecImgaeChange = (files, type, index) => {
    console.log(files, type, index);
    setRecImg(files);
  }

  //专家回执单图片地址
  const [expertImgAddress,setExpertImgAddress] = useState([]);
   const onExpertImgaeChange = (files, type, index) => {
    console.log(files, type, index);
    setExpertImgAddress(files);
  }

 //专家回执单图片地址
 const [recExpertImg,setEecExpertImg] = useState([]);
 const onExpertRecImgaeChange = (files, type, index) => {
  console.log(files, type, index);
  setEecExpertImg(files);
}

 //图片上传
 const upload =  (files) => {
        let resList = []; 
        files.map(item=>{
            let formData = new FormData();
            let file = item.file;
            formData.append('file', file);
            formData.append('model', 'union')  
            let res =  reqUpload(formData);
            resList.push(res);
        })
        return resList;
}
   //表单选中索引
   const [selectIndex,setSelectIndex] = useState(0);
   //选择联盟表单
   const onRadioChange =(i)=>{
      setSelectIndex(i);
   }

    //点击提交
  const clickSubmit = () =>{
    if (selectIndex===0) {
        submitForm();
        return
    }
    submitExpert();
  }

  //提交专家
  const submitExpert =() =>{
    let memberName = getFieldValue('name');
    let topTitle = getFieldValue('topTitle');
    let jobTitle = getFieldValue('jobTitle');
    let workUnit = getFieldValue('workUnit');
    let researchArea = getFieldValue('researchArea');
    let summary = getFieldValue('summary');
    let cityData = getFieldValue('cityData');
    if (!memberName) {
        Toast.info('请填写姓名');
        return
    }
    if (!topTitle) {
        Toast.info('请填写职称');
        return
    }
    if (!jobTitle) {
        Toast.info('请填写职务/头衔');
        return
    }
    if (!workUnit) {
        Toast.info('请填写工作单位');
        return
    }
    if (!researchArea || researchArea.length===0) {
        Toast.info('请选择研究领域');
        return
    }
    if (!researchContent || researchContent.length===0) {
        Toast.info('请填写研究方向');
        return
    }
    if (!cityData || cityData.length===0) {
        Toast.info('请选择联系地址');
        return
    }
    if (!summary) {
        Toast.info('请填写简要介绍');
        return
    }
    let params = {memberName,topTitle,jobTitle,summary,workUnit};
    params.researchArea = researchArea.join(',');
    params.research = researchContent.join(',');
    params.city = cityData[0];
    params.province = cityData[1];
    params.invitedCode = "WxuidB2fVxg=";
    
    
    //图片上传
    let imgResult1 =  upload(expertImgAddress);
    let imgResult2 =  upload(recExpertImg);
    let userInfo = JSON.parse(sessionStorage.getItem('userInfo'))
    params.userId = userInfo.userId;
    params.memberPhone = userInfo.phoneNumber;
    Promise.all([...imgResult1,...imgResult2]).then(pRes=>{
        console.log(pRes);
        params.headPortrait = pRes[0].data.ret ? pRes[0].data.data :'';
        if (pRes.length===2){
         params.receiptsUrl = pRes[1].data.ret ? pRes[1].data.data :'';
        } 
        if (pRes.length===3){
         params.receiptsUrl = `${pRes[1].data.data},${pRes[2].data.data}`  ;
        } 
        console.log(params)
        reqExpertMember(params).then(res=>{
            console.log('加入结果',res);
            if (res.data.ret) {
                Toast.success('加入申请已提交')
                return
            }
            Toast.info(res.data.errmsg)
        })
    })

    console.log(memberName,topTitle,jobTitle,researchArea,summary,researchContent); 
  }
   //研究领域
   const [researchDeriction,setResearchDeriction] = useState('');
   const [directionModal, setDirectionModal] = useState(false);//研究方向modal
   const [searchValue,setSearchValue] = useState(''); //研究方向
   const [researchContent,setResearchContent] = useState([]);
   //打开研究方向
    const toSelectPage = () => {
        setDirectionModal(true);
    }
    //关闭研究方向model
    const onDirectionClose = () => {
        setDirectionModal(false);
    }
     //输入框值改变
     const handleInputChange = (e)=>{
        setSearchValue(e.target.value);
    }
     //更新研究方向名称
     const updateResearchName = (v) => {
        console.log(v)
        if (v.length === 0) {
            setResearchDeriction('');
        } else if (v.length === 1) {
            setResearchDeriction(v[0]);
        } else {
            let lastResearchArea = v[0] + '，+';
            setResearchDeriction(lastResearchArea);
        }
    };
    //添加研究方向item
    const addResearchItem = ()=>{
        if (searchValue===''){
            Toast.info('请输入研究方向', 1);
            return
        }
        if(researchContent.includes(searchValue)){
            Toast.info('请勿重复输入');
            return
        }
        let oldResearchContent = researchContent;
        let researchItem = oldResearchContent.push(searchValue);
        setResearchContent([...oldResearchContent]);
        setSearchValue('');
        updateResearchName(oldResearchContent);
    }
    //删除研究方向item
    const deleteResearchItem = (index)=>{
        let researchContentText = researchContent;
        researchContentText.splice(index,1);
        setResearchContent([...researchContentText]);
        updateResearchName(researchContentText);

    }
    

   
    return (
        <div className='expert-alliance-box'>
            <div className="alliance-content">
            <div className="nav">
            <NavBar
                    mode="light"
                    icon={<Icon type="left" color={'rgba(0, 0, 0, 0.9)'} />}
                    onLeftClick={() => clickLeft()}
                >加入联盟</NavBar>
            </div>
                
                <div className="allian-body">
                <div className="allain-warp">
                     <div onClick={() => onRadioChange(0)} className={selectIndex===0?"allain-content-active margin-15":"allain-content margin-15"}>
                       <CheckboxItem checked={selectIndex===0}  onChange={() => onRadioChange(0)}>
                               单位
                       </CheckboxItem>
                      <img src={img1}></img> 
                    </div>  
                     <div onClick={() => onRadioChange(1)} className={selectIndex===1?"allain-content-active":"allain-content"}>
                      <CheckboxItem checked={selectIndex===1}  onChange={() => onRadioChange(1)}>
                                专家
                       </CheckboxItem>
                         <img src={img2}></img> 
                     </div>
                </div>

                <div className="join-notice" onClick={()=>history.push('/h5-receipt-content')}>
                    <div className="join-text">完善信息前请先填写回执单及查看加入流程</div>
                     <Icon color="rgba(178, 137, 58, 1)"  type="right" size="xs" />
                </div>

            {
                selectIndex===0 ? (
                    <div className='expert-allianc-form'>
                    <List style={{ backgroundColor: 'white' }} className={'picker-list-null'}>
                    <Picker  data={companyNameData} cols={1} {...getFieldProps('memberName',{
                                        rules: [{ required: true ,message:'请输入单位名称'}],
                                    })} className="forss">
                        <List.Item arrow="horizontal">单位名称</List.Item>
                    </Picker>
                    </List>
                    <List style={{ backgroundColor: 'white' }} className={'picker-list-null'}>
                    <Picker data={companyTypeData} cols={1} {...getFieldProps('companyType',
                                {
                                        rules: [{ required: true ,message:'请选择单位性质'}],
                                    })} className="forss">
                        <List.Item arrow="horizontal">单位性质</List.Item>
                    </Picker>
                    </List>
                    <List style={{ backgroundColor: 'white' }} className={'picker-list-null'}>
                    <InputItem
                        type={'number'}
                        {...getFieldProps('companyCode', {
                            rules: [{ required: true ,message:'请输入统一信用代码'}],
                        })}
                        maxLength='18'
                        placeholder="请输入统一信用代码"
                        clear
                    >统一信用代码</InputItem>
                    </List>
                    <List style={{ backgroundColor: 'white' }} className={'picker-list-null'}>
                    <InputItem
                        type={'text'}
                        {...getFieldProps('linkPerson', {
                            rules: [{ required: true ,message:'请输入联系人'}],
                        })}
                        placeholder="请输入联系人"
                        clear
                    >联系人</InputItem>
                    </List>     
                    <List style={{ backgroundColor: 'white' }} className={'picker-list-null'}>
                        <Picker extra="请选择联系地址"
                                data={district}
                                cols={'2'}
                                title="联系地址"
                                {...getFieldProps('district',
                                    {
                                        rules: [{ required: true ,message:'请选择联系地址'}],
                                    }
                                )}
                        >
                            <List.Item arrow="horizontal">联系地址</List.Item>
                        </Picker>
                    </List>
                    <List className="gobal_head" renderHeader={() => '上传营业执照'}>
                        <div className='upload-publicity-photo'>
                            <div className='upload-publicity-img'>
                                <ImagePicker
                                  accept="image/jpeg,image/jpg,image/png"
                                  files={imgAddress}
                                  onChange={onImgaeChange}
                                  onImageClick={(index, fs) => console.log(index, fs)}
                                  selectable={imgAddress.length < 1}
                                  multiple={false} />
                            </div>
                            <div className='upload-publicity-text'>
                                <h3>作为审核材料</h3>
                                <h3>图片格式为jpg、png、jpeg</h3>
                            </div>
                        </div>
                    </List>
                    <List className="gobal_head" renderHeader={() => '上传回执单'}>
                        <div className='upload-publicity-file'>
                            <div className='upload-publicity-file-img'>
                            <ImagePicker
                                  accept="image/jpeg,image/jpg,image/png"
                                  files={recImg}
                                  onChange={onRecImgaeChange}
                                  onImageClick={(index, fs) => console.log(index, fs)}
                                  selectable={recImg.length < 2}
                                  multiple={false} />
                            </div>
                            <div className='upload-publicity-file-text'>
                                <h3>最多上传2张，作为审核材料，图片格式为jpg、png、jpeg</h3>
                            </div>
                        </div>
                    </List>
                </div>
                ):( <div className="person-warp expert-allianc-form">
                  <List style={{ backgroundColor: 'white' }} className={'picker-list-null'}>
                    <InputItem
                        type={'text'}
                        {...getFieldProps('name')}
                        placeholder="请输入姓名"
                        clear
                    >姓名</InputItem>
                    </List>
                    <List style={{ backgroundColor: 'white' }} className={'picker-list-null'}>
                    <InputItem
                        type={'text'}
                        {...getFieldProps('workUnit')}
                        placeholder="请输入您的工作单位"
                        clear
                    >职称</InputItem>
                    </List>
                    <List style={{ backgroundColor: 'white' }} className={'picker-list-null'}>
                    <InputItem
                        type={'text'}
                        {...getFieldProps('topTitle')}
                        placeholder="请输入您的职称"
                        clear
                    >职称</InputItem>
                    </List>
                    <List style={{ backgroundColor: 'white' }} className={'picker-list-null'}>
                    <InputItem
                        type={'text'}
                        {...getFieldProps('jobTitle')}
                        placeholder="请输入您的职务/头衔"
                        clear
                    >职务/头衔</InputItem>
                    </List>
                    <List style={{ backgroundColor: 'white' }} className={'picker-list-null'}>
                    <Picker  data={searchAreaData} cols={1} {...getFieldProps('researchArea')} className="forss">
                        <List.Item arrow="horizontal">研究领域</List.Item>
                    </Picker>
                    </List>
                    <List style={{ backgroundColor: 'white' }} className={'picker-list-null'}>
                        <Picker extra="请选择联系地址"
                                data={district}
                                cols={'2'}
                                title="联系地址"
                                {...getFieldProps('cityData')}
                        >
                            <List.Item arrow="horizontal">联系地址</List.Item>
                        </Picker>
                    </List>
                    <List onClick={toSelectPage} style={{ backgroundColor: 'white' }} className={'picker-list-null'}>
                    <InputItem
                    type={'text'}
                    disabled={true}
                    {...getFieldProps('research')}
                    value={researchDeriction}
                    placeholder="请输入研究方向"
                    clear
                  >研究方向</InputItem>
                  </List>
                    <List renderHeader={() => '简要介绍'}>
                    <TextareaItem
                        placeholder='请输入您的简要介绍'
                        {...getFieldProps('summary')}
                        rows={5}
                    />
                </List>
                    <List renderHeader={() => '上传宣传照'}>
                        <div className='upload-publicity-photo'>
                            <div className='upload-publicity-img'>
                                <ImagePicker
                                  accept="image/jpeg,image/jpg,image/png"
                                  files={expertImgAddress}
                                  onChange={onExpertImgaeChange}
                                  onImageClick={(index, fs) => console.log(index, fs)}
                                  selectable={expertImgAddress.length < 1}
                                  multiple={false} />
                            </div>
                            <div className='upload-publicity-text'>
                                <h3>图片格式为jpg、png、jpeg</h3>
                            </div>
                        </div>
                    </List>
                    <List renderHeader={() => '上传回执单'}>
                        <div className='upload-publicity-file'>
                            <div className='upload-publicity-file-img'>
                            <ImagePicker
                                  accept="image/jpeg,image/jpg,image/png"
                                  files={recExpertImg}
                                  onChange={onExpertRecImgaeChange}
                                  onImageClick={(index, fs) => console.log(index, fs)}
                                  selectable={recExpertImg.length < 2}
                                  multiple={false} />
                            </div>
                            <div className='upload-publicity-file-text'>
                                <h3>最多上传2张，作为审核材料，图片格式为jpg、png、jpeg</h3>
                            </div>
                        </div>
                    </List>
                    
                   </div> 
                )
            }
            
                </div>
            <div className='submit-button-box'>
                <Button className='submit-button' onClick={clickSubmit} style={{ fontSize: '16px' }} type="primary">提交</Button>
            </div>
            </div>
            {/*研究方向*/}
            <Modal
                popup
                title={'研究方向'}
                className='direction-modal'
                closable={true}
                visible={directionModal}
                onClose={() => onDirectionClose()}
                animationType="slide-up"
            >
                <div className='research-area'>
                    <div className='research-content'>
                        <div className='research-input'>
                            <input  value={searchValue} onChange={handleInputChange} placeholder='请输入研究方向' type='text' />
                            <button onClick={()=>addResearchItem()}>添加</button>
                        </div>
                        <div className='research-text-box'>
                            {
                                researchContent.map((item,index)=>{
                                    return (
                                        <div key={index} onClick={()=>deleteResearchItem(index)} className='research-text-item'>
                                            <span>{item}</span><Icon  color='rgba(148, 190, 252, 1)' type="cross" size='xs' />
                                        </div>
                                    )
                                })
                            }
                        </div>
                    </div>
                </div>
            </Modal>
                
        </div>
    )
}

const WrapperForm = createForm()(InviteAlliance);


export default (WrapperForm);

